import Compute from '../libs/Compute'
import toNumber from '../utils/tools';
import ResultComponent from '../components/result';
export default class Calculator extends Compute {
    constructor(el) {
        super();
        // 模块名称
        this.name = "Calculator";
        this.result = el.querySelector('.result');
        this.inputs = el.querySelectorAll('input');
        this.btnGroup = el.querySelector('.btn-group');
        this.resultComponent = new ResultComponent();
    }
    // 初始化方法
    init() {
        // this.bindEvent();
        this.render();
    }
    render() {
        // 声明文档碎片
        const oFrag = document.createDocumentFragment();
        // 使用文档碎片临时保存每一个元素
        oFrag.appendChild(this.resultComponent.tpl());
        // 将文档碎片插入父元素中
        this.el.appendChild(oFrag);
    }
    // 事件处理函数
    bindEvent() {
        /**
         * this.btnClick.bind(this)
         * bind改变this指向始终指向被点击的按钮
         */
        this.btnGroup.addEventListener('click', this.btnClick.bind(this), false);
    }
    btnClick(ev) {
        ev = ev || window.event;
        const tar = ev.target || ev.srcElement;
        const tagName = tar.tagName.toLowerCase();
        /**
         * 如果点击的是按钮
         * 取出自定义属性data-method
         */
        if(tagName==="button"){
            const method = tar.getAttribute('data-method');
            const fval = toNumber(this.inputs[0].value) || 0;
            const sval = toNumber(this.inputs[1].value) || 0;
            this.setResult(method,fval,sval);
        }
    }
    setResult(method,fval,sval) {
        this.result.innerText = this[method](fval, sval);
    }
}